package com.flow.framework.core.pojo.vo;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;

/**
 * 模块调用分页对象传输，对象构造参考
 * com.flow.framework.persistence.util.PersistencePageUtil和com.flow.framework.base.util.BasePageUtil
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/2/5
 */
@Slf4j
@Data
@NoArgsConstructor
@EqualsAndHashCode()
public class PageModuleVo<T> {

    /**
     * 当前页数
     */
    private long current;

    /**
     * 数据总数
     */
    private long total;

    /**
     * 分页大小
     */
    private long size;

    /**
     * 总页数
     */
    private long pages;

    /**
     * 分页数据
     */
    private List<T> records = Collections.emptyList();

    private PageModuleVo(long current, long total, long size, long pages, List<T> records) {
        this.current = current;
        this.total = total;
        this.size = size;
        this.pages = pages;
        if (null != records) {
            this.records = records;
        }
    }

    /**
     * 构建模块调用分页响应结果
     *
     * @param current 当前页数
     * @param total   数据总数
     * @param size    分页大小
     * @param records 分页数据
     * @param <T>     T
     * @return 模块调用分页响应
     */
    public static <T> PageModuleVo<T> build(long current, long total, long size, List<T> records) {
        if (size <= 0) {
            log.error("page size can't less than one");
            throw new CheckedException(SystemErrorCode.PARAMS_ERROR);
        }
        if (0 == total) {
            return new PageModuleVo<T>(current, total, size, 0, records);
        }
        long tempPages = total / size;
        if (total % size != 0) {
            tempPages++;
        }
        return new PageModuleVo<T>(current, total, size, tempPages, records);
    }
}
